package thread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: Multhread
 * @description: 锁, 互斥机制
 * @author: zhanghz001
 * @create: 2021-03-04 20:37
 **/
public class BadCounter {
    private static int i = 0;
    
    public int get() {
        return i;
    }
    
    ReentrantLock lock = new ReentrantLock();
    
    // public void inc() {
    // public synchronized void inc() {
    public void inc() {
        lock.lock();
        try {
            int j = get();
            try {
                Thread.sleep(100);
                j++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i = j;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            
            lock.unlock();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        final BadCounter counter = new BadCounter();
//不使用线程10次，对比使用线程10次，看结果
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    counter.inc();
                }
            }).start();
        }
        Thread.sleep(3000);
        //理论上10才对。可是....
        System.out.println(counter.i);
    }
}
